package com.jhgsys.internal.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhgsys.internal.common.entity.MenuTree;
import com.jhgsys.internal.common.entity.MenuTreeNew;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.common.utils.TreeUtil;
import com.jhgsys.internal.system.dto.MenuDto;
import com.jhgsys.internal.system.dto.TenantDto;
import com.jhgsys.internal.system.entity.Menu;
import com.jhgsys.internal.system.mapper.MenuMapper;
import com.jhgsys.internal.system.service.IMenuService;
import com.jhgsys.internal.system.service.ITenantService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author MrBird
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private ITenantService tenantService;

    @Override
    public List<Menu> findUserPermissions(String username) {
        return this.baseMapper.findUserPermissions(username);
    }

    @Override
    public MenuTree<Menu> findUserMenus(String username) {
        List<Menu> menus = this.baseMapper.findUserMenus(username);
        List<MenuTree<Menu>> trees = this.convertMenus(menus);
        return TreeUtil.buildMenuTree(trees);
    }

    @Override
    public MenuTree<Menu> findMenus(Menu menu) {
        List<Menu> menus = this.baseMapper.selectListByRoles(menu);
        List<MenuTree<Menu>> trees = this.convertMenus(menus);
        return TreeUtil.buildMenuTree(trees);
    }

    /**
     * 查询第一级菜单count，parentId=0
     *
     * @return
     */
    @Override
    public Integer findMenusCount(Menu menu) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getDeletedFlg,0);
        queryWrapper.eq(Menu::getParentId,"0");
        if(StringUtils.isNotBlank(menu.getMenuName())){
            queryWrapper.like(Menu::getMenuName,menu.getMenuName());
        }
        return this.baseMapper.selectList(queryWrapper).size();
    }

    /**
     * 查询列表treeTable数据
     * @param request
     * @param menu
     * @return
     */
    @Override
    public MenuTreeNew<Menu> findMenusA(QueryRequest request,Menu menu) {
        Page<Menu> page = new Page<>(request.getPageNum(),request.getPageSize());
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getDeletedFlg,0);
        queryWrapper.eq(Menu::getParentId,"0");
        if(StringUtils.isNotBlank(menu.getMenuName())){
            queryWrapper.like(Menu::getMenuName,menu.getMenuName());
        }
        queryWrapper.orderByAsc(Menu::getOrderNum);

        FebsUtil.pageWrapper(page,request);
        IPage<Menu> pages = this.page(page,queryWrapper);
        List<Menu> parentMenus = pages.getRecords();

        Menu query = new Menu();
        query.setRoleIds(menu.getRoleIds());
        query.setDeletedFlg("0");
        List<Menu> menus = this.baseMapper.selectListByRoles(query);
        List<Menu> pagedMenus = this.getPagedMenus(parentMenus,menus);
        pagedMenus.addAll(parentMenus);
        List<MenuTreeNew<Menu>> trees = this.convertMenusNew(pagedMenus);
        return TreeUtil.buildMenuTreeNew(trees);
    }

    /**
     * 搜索返回数据，talbe形式
     * @param request
     * @param menu
     * @return
     */
    @Override
    public List<MenuTreeNew<Menu>> searchMenus(QueryRequest request,Menu menu) {
        Page<Menu> page = new Page<>(request.getPageNum(),request.getPageSize());
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getDeletedFlg,0);
        if(StringUtils.isNotBlank(menu.getMenuName())){
            queryWrapper.like(Menu::getMenuName,menu.getMenuName());
        }
        queryWrapper.orderByAsc(Menu::getOrderNum);

        FebsUtil.pageWrapper(page,request);
        IPage<Menu> pages = this.page(page,queryWrapper);
        List<Menu> menus = pages.getRecords();

        List<MenuTreeNew<Menu>> trees = this.convertMenusNew(menus);
        return trees;
    }

    /**
     * 搜索返回数据count
     * @param menu
     * @return
     */
    @Override
    public Integer serchMenusCount(Menu menu) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getDeletedFlg,0);
        if(StringUtils.isNotBlank(menu.getMenuName())){
            queryWrapper.like(Menu::getMenuName,menu.getMenuName());
        }
        queryWrapper.orderByAsc(Menu::getOrderNum);
        return this.baseMapper.selectList(queryWrapper).size();
    }

    /**
     * 新增编辑页面，菜单下拉treeSelect
     * @param menu
     * @return
     */
    @Override
    public Object findMenusB(Menu menu) {
        menu.setDeletedFlg("0");
        List<Menu> menus = this.baseMapper.selectListByRoles(menu);
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getParentId,"0");
        queryWrapper.eq(Menu::getDeletedFlg,"0");
        queryWrapper.orderByAsc(Menu::getOrderNum);
        List<Menu> pMenus = this.baseMapper.selectList(queryWrapper);
        List<Map<String,Object>> trees = this.buildTree(pMenus,menus);
        return trees;
    }

    /**
     * 查找所有菜单/按钮 jsonArray形式
     *
     * @param menu
     * @return
     */
    @Override
    public List<Menu> findMenusNew(Menu menu) {
        List<Menu> menus = this.baseMapper.selectListByRoles(menu);
        return menus;
    }

    @Override
    public List<Menu> findMenuList(Menu menu) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(menu.getMenuName())) {
            queryWrapper.lambda().like(Menu::getMenuName, menu.getMenuName());
        }
        queryWrapper.lambda().orderByAsc(Menu::getMenuId).orderByAsc(Menu::getOrderNum);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据id查找menu
     *
     * @param menuId
     * @return
     */
    @Override
    public MenuDto findMenuById(String menuId) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(menuId)){
            queryWrapper.eq(Menu::getMenuId,menuId);
        }
        Menu menu = this.baseMapper.selectOne(queryWrapper);
        MenuDto m = BeanHelper.copyProperties(menu,MenuDto.class);
        if(menu.getParentId() != "0"){
            LambdaQueryWrapper<Menu> query = new LambdaQueryWrapper<>();
            query.eq(Menu::getMenuId,menu.getParentId());
            Menu parent = this.baseMapper.selectOne(query);
            if(ObjectUtils.isNotEmpty(parent)){
                m.setParentName(parent.getMenuName());
            }
        }
        return m;
    }

    @Override
    @Transactional
    public void createMenu(Menu menu) {
        if(StringUtils.isBlank(menu.getParentId())){
            menu.setParentId("0");
        }
        menu.setCreateTime(new Date());
        this.setMenu(menu);
        this.baseMapper.insert(menu);
    }


    @Override
    @Transactional
    public void updateMenu(Menu menu) {
        menu.setModifyTime(new Date());
//        this.setMenu(menu);
        this.baseMapper.updateById(menu);
    }


    @Override
    public List<Menu> findRoleMenus(String roleId) {
        return this.baseMapper.findRoleMenus(roleId);
    }

    @Override
    public List<Menu> findTenantMenus(String tenantId) {
        TenantDto dbTenant = tenantService.findTenantByTenantId(tenantId);
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getDeletedFlg,'0');
        queryWrapper.eq(Menu::getParentId,Menu.TOP_NODE);
        if(null == dbTenant || "2".equals(dbTenant.getTenantCategory())){
            queryWrapper.eq(Menu::getGrantedSubsidiaryFlg,'1');
        }

        List<Menu> menuList = this.baseMapper.selectList(queryWrapper);
        return menuList;
    }

    private List<MenuTree<Menu>> convertMenus(List<Menu> menus) {
        List<MenuTree<Menu>> trees = new ArrayList<>();
        menus.forEach(menu -> {
            MenuTree<Menu> tree = new MenuTree<>();
            tree.setId(String.valueOf(menu.getMenuId()));
            tree.setParentId(String.valueOf(menu.getParentId()));
            tree.setTitle(menu.getMenuName() + (!"1".equals(menu.getStatus()) ? "(禁用)":""));
            tree.setIcon(menu.getIcon());
            tree.setHref(menu.getUrl());
            tree.setData(menu);
            trees.add(tree);
        });
        return trees;
    }

    private List<MenuTreeNew<Menu>> convertMenusNew(List<Menu> menus) {
        List<MenuTreeNew<Menu>> trees = new ArrayList<>();
        menus.forEach(menu -> {
            MenuTreeNew<Menu> tree = new MenuTreeNew<>();
            tree.setId(String.valueOf(menu.getMenuId()));
            tree.setParentId(String.valueOf(menu.getParentId()));
            tree.setTitle(menu.getMenuName() + (!"1".equals(menu.getStatus()) ? "(禁用)":""));
            tree.setIcon(menu.getIcon());
            tree.setUrl(menu.getUrl());
            tree.setData(menu);
            tree.setName(menu.getMenuName());
            tree.setPerms(menu.getPerms());
            tree.setOrderNum(menu.getOrderNum());
            tree.setType(menu.getType());
            tree.setStatus(menu.getStatus());
            trees.add(tree);
        });
        return trees;
    }

    private void setMenu(Menu menu) {
        if (menu.getParentId() == null) {
            menu.setParentId(String.valueOf(Menu.TOP_NODE));
        }
        if (Menu.TYPE_BUTTON.equals(menu.getType())) {
            menu.setUrl(null);
            menu.setIcon(null);
        }
    }

    /**
     * 批量删除菜单，即更新删除标记、删除时间和删除人
     *
     * @param menuIds
     * @param menu
     */
    @Override
    public void updateMenuDeletedFlg(String menuIds, Menu menu) {
        List<String> idlist = getId(menuIds);
        this.baseMapper.update(menu, new LambdaQueryWrapper<Menu>().in(Menu::getMenuId, idlist));
    }

    /**
     * 获取级联id
     *
     * @param ids
     * @return
     */
    private List<String> getId(String ids) {
        String[] idArrs = ids.split(StringPool.COMMA);
        //传的id
        List<String> idlist = Arrays.asList(idArrs);
        List arrList = new ArrayList(idlist);

        //临时list ，存方存在下级元素的id
        List<String> tempList = new ArrayList<>();
        List<Menu> menus = baseMapper.selectList(new LambdaQueryWrapper<Menu>().in(Menu::getParentId, arrList));
        if (menus != null && !menus.isEmpty()) {
            //根据parentid查询到的id 主要是判断是否存在子元素。
            for (Menu menu : menus) {
                tempList.add(String.valueOf(menu.getMenuId()));
            }
            tempList.forEach((str) -> arrList.add(str));
        }

        while (menus != null && !menus.isEmpty()) {
            menus = baseMapper.selectList(new LambdaQueryWrapper<Menu>().in(Menu::getParentId, tempList));

            if (menus != null && !menus.isEmpty()) {
                //根据parentid查询到的id 主要是判断是否存在子元素。
                tempList.clear();
                for (Menu menu : menus) {
                    tempList.add(String.valueOf(menu.getMenuId()));
                }
                arrList.addAll(tempList);
            }
        }
        arrList.forEach(x -> System.out.println(x));
        return arrList;
    }

    /**
     * 菜单excel导出
     *
     * @param menu
     * @param response
     * @author qiny
     * @date 2019-07-24
     */
    @Override
    public void exportData(Menu menu, HttpServletResponse response) {

        // 1.创建一个workbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 2.在workbook中添加一个sheet，对应Excel中的一个sheet
        HSSFSheet sheet = wb.createSheet("菜单信息");
        // 3.在sheet中添加表头第0行，老版本poi对excel行数列数有限制short
        HSSFRow row = sheet.createRow(0);
        // 4.创建单元格，设置值表头，设置表头居中
        HSSFCellStyle style = wb.createCellStyle();

        // 设置表头
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("名称");
        cell.setCellStyle(style);

        cell = row.createCell(1);
        cell.setCellValue("URL");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("权限");
        cell.setCellStyle(style);

        cell = row.createCell(3);
        cell.setCellValue("图标");
        cell.setCellStyle(style);

        cell = row.createCell(4);
        cell.setCellValue("类型");
        cell.setCellStyle(style);

        cell = row.createCell(5);
        cell.setCellValue("创建人");
        cell.setCellStyle(style);

        cell = row.createCell(6);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);

        cell = row.createCell(7);
        cell.setCellValue("更新人");
        cell.setCellStyle(style);

        cell = row.createCell(8);
        cell.setCellValue("更新时间");
        cell.setCellStyle(style);

        cell = row.createCell(9);
        cell.setCellValue("删除人");
        cell.setCellStyle(style);

        cell = row.createCell(10);
        cell.setCellValue("删除时间");
        cell.setCellStyle(style);

        cell = row.createCell(11);
        cell.setCellValue("删除标记");
        cell.setCellStyle(style);

        String fileName = "菜单信息表" + (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            List<Menu> lists = this.baseMapper.exportData(menu);
            // 循环将数据写入Excel
            for (int i = 0; i < lists.size(); i++) {
                row = sheet.createRow(i + 1);
                Menu temp = lists.get(i);
                // 创建单元格，设置值
                row.createCell(0).setCellValue(converNull(temp.getMenuName()));
                row.createCell(1).setCellValue(converNull(temp.getUrl()));
                row.createCell(2).setCellValue(converNull(temp.getPerms()));
                row.createCell(3).setCellValue(converNull(temp.getIcon()));
                if("0".equals(converNull(temp.getType()))){
                    row.createCell(4).setCellValue("菜单");
                }else if("1".equals(converNull(temp.getType()))){
                    row.createCell(4).setCellValue("按钮 ");
                }
                row.createCell(5).setCellValue(converNull(temp.getCreatedBy()));
                row.createCell(6).setCellValue(converNull(temp.getCreateTime()));
                row.createCell(7).setCellValue(converNull(temp.getUpdatedBy()));
                row.createCell(8).setCellValue(converNull(temp.getModifyTime()));
                row.createCell(9).setCellValue(converNull(temp.getDeletedBy()));
                row.createCell(10).setCellValue(converNull(temp.getDeletedTime()));
                if("0".equals(converNull(temp.getDeletedFlg()))){
                    row.createCell(11).setCellValue("未删除");
                }else if ("1".equals(converNull(temp.getDeletedFlg()))) {
                    row.createCell(11).setCellValue("已删除");
                }
            }

            wb.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName + ".xls").getBytes("GB2312"), StandardCharsets.ISO_8859_1));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;

            try {
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(out);
                byte[] buff = new byte[2048];
                int bytesRead;
                // Simple read/write loop.
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public MenuTree<Menu> findChildTenantMenuTree() {

        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getDeletedFlg,'0');
        queryWrapper.eq(Menu::getParentId,String.valueOf(Menu.TOP_NODE));
        queryWrapper.eq(Menu::getGrantedSubsidiaryFlg,'1');
        List<Menu> menuList = this.baseMapper.selectList(queryWrapper);
        //获取公司对应菜单id 取集合
        List<String> parentList = menuList.stream().map(Menu::getMenuId).collect(Collectors.toList());
        //获取所有菜单
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getDeletedFlg,'0');
        List<Menu> allMenuList = this.baseMapper.selectList(queryWrapper);
        //将所有菜单中，父菜单节点属于公司集合的过滤出 得出父菜单下属所有二级菜单
        List<Menu> secondList = allMenuList.stream().filter(item->parentList.contains(item.getParentId())).collect(Collectors.toList());
        //获取二级菜单id 取集合
        List<String> secondIdList = secondList.stream().map(Menu::getMenuId).collect(Collectors.toList());
        //根据二级菜单Id获取三级目录菜单
        List<Menu> thirdList = allMenuList.stream().filter(item->secondIdList.contains(item.getParentId())).collect(Collectors.toList());
        //父子集合
        menuList.addAll(secondList);
        menuList.addAll(thirdList);
        List<MenuTree<Menu>> trees = this.convertMenus(menuList);
        return TreeUtil.buildMenuTree(trees);
    }

    /**
     * null 转换
     *
     * @param obj
     * @return 返回字符串
     */
    private static String converNull(Object obj) {
        return Optional.ofNullable(obj).map(Object::toString).orElse("");
    }

    /**
     * 组装treeTable数据
     * @param parentMenus
     * @param menus
     * @return
     */
    private List<Menu> getPagedMenus(List<Menu> parentMenus,List<Menu> menus){
        List<Menu> pagedMenus = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(parentMenus)){
            parentMenus.forEach(m->{
                List<Menu> empty = new ArrayList<>();
                List<Menu> children = this.getChildren(menus,m.getMenuId(),empty);
                pagedMenus.addAll(children);
            });
        }
        return pagedMenus;
    }

    private List<Menu> getChildren(List<Menu> list,String pid,List<Menu> empty){
        for(Menu m:list){
            if(m.getParentId().equals(pid)){
                getChildren(list,m.getMenuId(),empty);
                empty.add(m);
            }
        }
        return empty;
    }

    /**
     * 组装treeSelect数据
     * @param parentMenus
     * @param menus
     * @return
     */
    private List<Map<String,Object>> buildTree(List<Menu> parentMenus,List<Menu> menus){
        List<Map<String,Object>> tree = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(parentMenus)){
            parentMenus.forEach(m->{
                Map<String,Object> map = new HashMap<>();
                map.put("id",m.getMenuId());
                map.put("name",m.getMenuName());
                List<Map<String,Object>> empty = new ArrayList<>();
                List<Map<String,Object>> children = this.buildChildren(menus,m.getMenuId());
                map.put("children",children);
                tree.add(map);
            });
        }
        return tree;
    }

    private List<Map<String,Object>> buildChildren(List<Menu> list,String pid){
        List<Map<String,Object>> empty = new ArrayList<>();
        for(Menu m:list){
            Map<String,Object> child = new HashMap<>();
            if(m.getParentId().equals(pid)){
                child.put("id",m.getMenuId());
                child.put("name",m.getMenuName());
                child.put("children",buildChildren(list,m.getMenuId()));
                empty.add(child);
            }
        }
        if(empty.size()>0){
            return empty;
        }else{
            return null;
        }
    }



}
